package com.ruoyi.imports.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.imports.domain.*;
import com.ruoyi.imports.mapper.TdProcessDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.imports.mapper.TdProcessDataTypeMapper;
import com.ruoyi.imports.service.ITdProcessDataTypeService;

/**
 * 过程数据检测类型Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-14
 */
@Service
public class TdProcessDataTypeServiceImpl implements ITdProcessDataTypeService {
    // 日期格式化工具（仅处理日期部分）
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy年M月d日", Locale.CHINESE);

    static {
        DATE_FORMAT.setLenient(false); // 严格校验日期格式
    }

    @Autowired
    private TdProcessDataTypeMapper tdProcessDataTypeMapper;

    @Autowired
    private TdProcessDataMapper tdProcessDataMapper;

    /**
     * 查询过程数据检测类型
     *
     * @param id 过程数据检测类型主键
     * @return 过程数据检测类型
     */
    @Override
    public TdProcessDataType selectTdProcessDataTypeById(Long id) {
        return tdProcessDataTypeMapper.selectTdProcessDataTypeById(id);
    }

    /**
     * 查询过程数据检测类型列表
     *
     * @param tdProcessDataType 过程数据检测类型
     * @return 过程数据检测类型
     */
    @Override
    public List<TdProcessDataType> selectTdProcessDataTypeList(TdProcessDataType tdProcessDataType) {
        return tdProcessDataTypeMapper.selectTdProcessDataTypeList(tdProcessDataType);
    }

    /**
     * 新增过程数据检测类型
     *
     * @param tdProcessDataType 过程数据检测类型
     * @return 结果
     */
    @Override
    public int insertTdProcessDataType(TdProcessDataType tdProcessDataType) {
        tdProcessDataType.setCreateTime(DateUtils.getNowDate());
        return tdProcessDataTypeMapper.insertTdProcessDataType(tdProcessDataType);
    }

    /**
     * 修改过程数据检测类型
     *
     * @param tdProcessDataType 过程数据检测类型
     * @return 结果
     */
    @Override
    public int updateTdProcessDataType(TdProcessDataType tdProcessDataType) {
        tdProcessDataType.setUpdateTime(DateUtils.getNowDate());
        return tdProcessDataTypeMapper.updateTdProcessDataType(tdProcessDataType);
    }

    /**
     * 批量删除过程数据检测类型
     *
     * @param ids 需要删除的过程数据检测类型主键
     * @return 结果
     */
    @Override
    public int deleteTdProcessDataTypeByIds(Long[] ids) {
        return tdProcessDataTypeMapper.deleteTdProcessDataTypeByIds(ids);
    }

    /**
     * 删除过程数据检测类型信息
     *
     * @param id 过程数据检测类型主键
     * @return 结果
     */
    @Override
    public int deleteTdProcessDataTypeById(Long id) {
        return tdProcessDataTypeMapper.deleteTdProcessDataTypeById(id);
    }

    @Override
    public void importProcessDataType(List<ProcessExcelData> excelDataList, Long projectId) {
        // 1. 基础校验
        if (excelDataList == null || excelDataList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }
// 2. 日期连续性校验（核心逻辑）
        validateDateContinuity(excelDataList);
        // 存储Excel行索引与主表ID的映射（用于关联子表）
        HashMap<Integer, Long> processToMainMap = new HashMap<>(excelDataList.size());
        try {
            //处理主表数据
            for (int i = 0; i < excelDataList.size(); i++) {
                ProcessExcelData processExcelData = excelDataList.get(i);
                TdProcessData tdProcessData = buildMainData(processExcelData, projectId);
                tdProcessDataMapper.insertTdProcessData(tdProcessData);
                processToMainMap.put(i, tdProcessData.getId());

            }

//            处理子表数据
            List<TdProcessDataType> typeDataList = new ArrayList<>();
            for (int i = 0; i < excelDataList.size(); i++) {
                ProcessExcelData processExcelData = excelDataList.get(i);
                Long mainId = processToMainMap.get(i);
                // 按类型添加子表数据
                typeDataList.add(buildTypeData(processExcelData, mainId, "COD"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "氨氮"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "硫氰酸根"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "PH"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "亚硝酸盐"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "硝酸盐"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "总磷"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "总氰"));
                typeDataList.add(buildTypeData(processExcelData, mainId, "碱度"));
            }
            // 批量插入子表
            if (!typeDataList.isEmpty()) {
                tdProcessDataTypeMapper.batchInsert(typeDataList);
            }
        } catch (Exception e) {
            // 异常捕获与日志
            throw new RuntimeException("导入失败：" + e.getMessage(), e);
        }
    }


    private TdProcessDataType buildTypeData(ProcessExcelData processExcelData, Long mainId, String type) {
        TdProcessDataType typeData = new TdProcessDataType();
        typeData.setProcessDataId(mainId);
        typeData.setType(type);

        // 设置通用字段
        Long userId = SecurityUtils.getUserId();
        typeData.setCreateUser(userId);
        typeData.setUpdateUser(userId);
        typeData.setCreateTime(new Date());
        typeData.setUpdateTime(new Date());
        typeData.setIsDeleted(0);

        if ("COD".equals(type)) {
            typeData.setRegulatingPool(processExcelData.getCodRegulatingPool());
            typeData.setPreExposure(processExcelData.getCodPreExposure());
            typeData.setPrimarySettlingTank(processExcelData.getCodPrimarySettlingTank());
            typeData.setAnaerobicTankA(processExcelData.getCodAnaerobicTankA());
            typeData.setAnaerobicTankB(processExcelData.getCodAnaerobicTankB());
            typeData.setAnoxicTankOneA(processExcelData.getCodAnoxicTankOneA());
            typeData.setAnoxicTankOneB(processExcelData.getCodAnoxicTankOneB());
            typeData.setAerobicTankOneA(processExcelData.getCodAerobicTankOneA());
            typeData.setAerobicTankOneB(processExcelData.getCodAerobicTankOneB());
            typeData.setAnoxicTankTwoA(processExcelData.getCodAnoxicTankTwoA());
            typeData.setAnoxicTankTwoB(processExcelData.getCodAnoxicTankTwoB());
            typeData.setAerobicTankTwoA(processExcelData.getCodAerobicTankTwoA());
            typeData.setAerobicTankTwoB(processExcelData.getCodAerobicTankTwoB());
            typeData.setSstOneA(processExcelData.getCodSstOneA());
            typeData.setSstOneB(processExcelData.getCodSstOneB());
            typeData.setCoagulationTank(processExcelData.getCodCoagulationTank());
        } else if ("氨氮".equals(type)) {
            typeData.setRegulatingPool(processExcelData.getNh3nRegulatingPool());
            typeData.setPreExposure(processExcelData.getNh3nPreExposure());
            typeData.setPrimarySettlingTank(processExcelData.getNh3nPrimarySettlingTank());
            typeData.setAnaerobicTankA(processExcelData.getNh3nAnaerobicTankA());
            typeData.setAnaerobicTankB(processExcelData.getNh3nAnaerobicTankB());
            typeData.setAnoxicTankOneA(processExcelData.getNh3nAnoxicTankOneA());
            typeData.setAnoxicTankOneB(processExcelData.getNh3nAnoxicTankOneB());
            typeData.setAerobicTankOneA(processExcelData.getNh3nAerobicTankOneA());
            typeData.setAerobicTankOneB(processExcelData.getNh3nAerobicTankOneB());
            typeData.setAnoxicTankTwoA(processExcelData.getNh3nAnoxicTankTwoA());
            typeData.setAnoxicTankTwoB(processExcelData.getNh3nAnoxicTankTwoB());
            typeData.setAerobicTankTwoA(processExcelData.getNh3nAerobicTankTwoA());
            typeData.setAerobicTankTwoB(processExcelData.getNh3nAerobicTankTwoB());
            typeData.setSstOneA(processExcelData.getNh3nSstOneA());
            typeData.setSstOneB(processExcelData.getNh3nSstOneB());
            typeData.setCoagulationTank(processExcelData.getNh3nCoagulationTank());
        } else if ("硫氰酸根".equals(type)) {
            typeData.setRegulatingPool(processExcelData.getScnRegulatingPool());
            typeData.setPreExposure(processExcelData.getScnPreExposure());
            typeData.setPrimarySettlingTank(processExcelData.getScnPrimarySettlingTank());
            typeData.setAnaerobicTankA(processExcelData.getScnAnaerobicTankA());
            typeData.setAnaerobicTankB(processExcelData.getScnAnaerobicTankB());
            typeData.setAnoxicTankOneA(processExcelData.getScnAnoxicTankOneA());
            typeData.setAnoxicTankOneB(processExcelData.getScnAnoxicTankOneB());
            typeData.setAerobicTankOneA(processExcelData.getScnAerobicTankOneA());
            typeData.setAerobicTankOneB(processExcelData.getScnAerobicTankOneB());
            typeData.setAnoxicTankTwoA(processExcelData.getScnAnoxicTankTwoA());
            typeData.setAnoxicTankTwoB(processExcelData.getScnAnoxicTankTwoB());
            typeData.setAerobicTankTwoA(processExcelData.getScnAerobicTankTwoA());
            typeData.setAerobicTankTwoB(processExcelData.getScnAerobicTankTwoB());
            typeData.setSstOneA(processExcelData.getScnSstOneA());
            typeData.setSstOneB(processExcelData.getScnSstOneB());
            typeData.setCoagulationTank(processExcelData.getScnCoagulationTank());
        } else if ("PH".equals(type)) {
            typeData.setRegulatingPool(processExcelData.getPhRegulatingPool());
            typeData.setPreExposure(processExcelData.getPhPreExposure());
            typeData.setPrimarySettlingTank(processExcelData.getPhPrimarySettlingTank());
            typeData.setAnaerobicTankA(processExcelData.getPhAnaerobicTankA());
            typeData.setAnaerobicTankB(processExcelData.getPhAnaerobicTankB());
            typeData.setAnoxicTankOneA(processExcelData.getPhAnoxicTankOneA());
            typeData.setAnoxicTankOneB(processExcelData.getPhAnoxicTankOneB());
            typeData.setAerobicTankOneA(processExcelData.getPhAerobicTankOneA());
            typeData.setAerobicTankOneB(processExcelData.getPhAerobicTankOneB());
            typeData.setAnoxicTankTwoA(processExcelData.getPhAnoxicTankTwoA());
            typeData.setAnoxicTankTwoB(processExcelData.getPhAnoxicTankTwoB());
            typeData.setAerobicTankTwoA(processExcelData.getPhAerobicTankTwoA());
            typeData.setAerobicTankTwoB(processExcelData.getPhAerobicTankTwoB());
            typeData.setSstOneA(processExcelData.getPhSstOneA());
            typeData.setSstOneB(processExcelData.getPhSstOneB());
            typeData.setCoagulationTank(processExcelData.getPhCoagulationTank());
        } else if ("亚硝酸盐".equals(type)) {
            typeData.setSstOneA(processExcelData.getNitritePrimarySstA());
            typeData.setSstOneB(processExcelData.getNitritePrimarySstB());
            typeData.setSstTwoA(processExcelData.getNitriteSecondarySstA());
            typeData.setSstTwoB(processExcelData.getNitriteSecondarySstB());
        } else if ("硝酸盐".equals(type)) {
            typeData.setSstOneA(processExcelData.getNitratePrimarySstA());
            typeData.setSstOneB(processExcelData.getNitratePrimarySstB());
            typeData.setSstTwoA(processExcelData.getNitrateSecondarySstA());
            typeData.setSstTwoB(processExcelData.getNitrateSecondarySstB());
        } else if ("总磷".equals(type)) {
            typeData.setSstTwoA(processExcelData.getTpSstA());
            typeData.setSstTwoB(processExcelData.getTpSstB());
        } else if ("总氰".equals(type)) {
            typeData.setSstTwoA(processExcelData.getTotalCyanideSstA());
            typeData.setSstTwoB(processExcelData.getTotalCyanideSstB());
        } else if ("碱度".equals(type)) {
            typeData.setRegulatingPool(processExcelData.getAlkalinityRegulatingPool());
            typeData.setAerobicTankOneA(processExcelData.getAlkalinityAerobicTankOneA());
            typeData.setAerobicTankOneB(processExcelData.getAlkalinityAerobicTankOneB());
            typeData.setAerobicTankTwoA(processExcelData.getAlkalinityAerobicTankTwoA());
            typeData.setAerobicTankTwoB(processExcelData.getAlkalinityAerobicTankTwoB());
        }
        return typeData;
    }

    private TdProcessData buildMainData(ProcessExcelData processExcelData, Long projectId) throws ParseException {
        TdProcessData mainData = new TdProcessData();
        mainData.setProjectId(projectId);

        //校验日期和时间非空
        String date = processExcelData.getDate();
        String time = processExcelData.getTime();
        if (date == null || time == null) {
            throw new IllegalArgumentException("日期或时间不能为空");
        }
        // 合并日期时间字符串（格式：yyyy年M月d日 HH:mm）
        String dateTimeStr = date.trim() + " " + time.trim();

        // 解析为Date（仅保留必要格式，适配Excel实际格式）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm", Locale.CHINESE);
        sdf.setLenient(false); // 严格校验格式
        Date recordTime = sdf.parse(dateTimeStr);
        mainData.setRecordTime(recordTime);

        // 设置创建/更新信息（按实际实体类字段调整）
        mainData.setCOD(processExcelData.getFinalCOD());
        mainData.setNh3N(processExcelData.getFinalNh3n());
        mainData.setPH(processExcelData.getFinalPH());
        mainData.setSulfide(processExcelData.getFinalSulfide());
        mainData.setVolatilePhenols(processExcelData.getFinalVolatilePhenols());
        mainData.setCyanide(processExcelData.getFinalCyanide());
        mainData.setTN(processExcelData.getFinalTN());
        mainData.setTP(processExcelData.getFinalTP());
        mainData.setPAH(processExcelData.getFinalPAH());
        mainData.setBaP(processExcelData.getFinalBaP());
        mainData.setBOD(processExcelData.getFinalBOD());
        mainData.setPetroleum(processExcelData.getFinalPetroleum());
        mainData.setSS(processExcelData.getFinalSS());
        mainData.setBenzene(processExcelData.getFinalBenzene());
        mainData.setNaphthalene(processExcelData.getFinalNaphthalene());
        mainData.setChroma(processExcelData.getFinalChroma());
        mainData.setCreateTime(new Date());
        mainData.setUpdateTime(new Date());
        mainData.setCreateBy(SecurityUtils.getUsername());
        mainData.setUpdateBy(SecurityUtils.getUsername());

        return mainData;
    }
    /**
     * 校验日期是否连续（按自然日顺序，不允许跳日）
     */
    private void validateDateContinuity(List<ProcessExcelData> dataList) {

        try {
            // 提取并解析所有日期
            List<Date> dateList = new ArrayList<>(dataList.size());
            for (ProcessExcelData data : dataList) {
                String dateStr = data.getDate();
                if (dateStr == null || dateStr.trim().isEmpty()) {
                    throw new IllegalArgumentException("第" + (dateList.size() + 1) + "行：日期不能为空");
                }
                // 解析日期字符串为Date（仅保留日期部分）
                Date date = DATE_FORMAT.parse(dateStr.trim());
                dateList.add(date);
            }

            // 校验连续日期
            for (int i = 1; i < dateList.size(); i++) {
                Date prevDate = dateList.get(i - 1);
                Date currDate = dateList.get(i);

                // 计算前一天日期
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(prevDate);
                calendar.add(Calendar.DAY_OF_YEAR, 1);
                Date expectedNextDate = calendar.getTime();

                // 比较当前日期是否为前一天的次日
                if (!currDate.equals(expectedNextDate)) {
                    // 格式化错误信息中的日期
                    String prevDateStr = DATE_FORMAT.format(prevDate);
                    String currDateStr = DATE_FORMAT.format(currDate);
                    throw new RuntimeException(
                            String.format("日期不连续：第%d行日期为%s，第%d行日期为%s（应为%s的次日）",
                                    i, prevDateStr, i + 1, currDateStr, prevDateStr)
                    );
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误：" + e.getMessage(), e);
        }
    }

}
